import re
import os
import sys
import msvcrt
'''
#def judge_new():
#	file0 = open(path + 'STUB_SrcFile.c','r+')
#	flg = 1
#	while True:
#			line = file0.readline()
#			if "cnt++" in line:
#				flg = 0
#				break
#			else:
#				pass
#			if not line :
#				break
#	file0.close()
#	return flg
'''


def del_useless(path):
    print("start:	deleting the useless")
    file0 = open(path + 'STUB_SrcFile.c', 'r+')
    file1 = open(path + 'STUB_SrcFile_temp.c', 'a+')
    while True:
        line = file0.readline()
        if ";" not in line and "VAR" not in line:
            file1.write(line)
        else:
            pass
        if not line:
            break

    file0.close()
    file1.close()
    print("end:	deleting the useless")
    return


def del_blank(path):
    print("start:	deleting blank line")
    file0 = open(path + 'STUB_SrcFile_temp.c', 'r+')
    file1 = open(path + 'STUB_SrcFile_temp_no_enter.c', 'a+')
    starflg = 0
    while True:
        line = file0.readline()
        if "/* WINAMS" in line:
            starflg = 1
            file1.write("\n")
        if line == "\n" and starflg == 0:
            pass
        else:
            file1.write(line)
        if not line:
            break

    file0.close()
    file1.close()
    print("end:	deleting blank line")
    return


def write_cnt(path):
    print("start:	write cnt")
    file0 = open(path + 'STUB_SrcFile_temp_no_enter.c', 'r+')
    file1 = open(path + 'STUB_SrcFile_temp1.c', 'a')
    temp = ""
    while True:
        # rolling1 : 每个函数加上cnt
        line = file0.readline()
        if " STUB_" in line:
            # 去括号。因为用search会多一个括号，目前找不到比较方便的方法，只能多一步减去
            pattern = re.sub(r'\(.*$', "", re.search(r'A.*\(', line).group())
            file1.write("unsigned char " + pattern + "_cnt;\n")
            file1.write(line)
            temp = "\t" + pattern + "_cnt++;\n"
        elif "{" in line:
            file1.write(line)
            file1.write(temp)
        else:
            file1.write(line)
        if not line:
            break

    file0.close()
    file1.close()
    print("end:	write cnt")
    return


def write_ret(path):
    print("start:	write ret")
    file1 = open(path + 'STUB_SrcFile_temp1.c', 'r+')
    file2 = open(path + 'STUB_SrcFile_temp2.c', 'a')
    temp = ""
    while True:
        # rolling2 : 加上返回值
        line = file1.readline()
        if " STUB_" in line and "void" not in line and "_cnt;" not in line:
            # 获取字符
            # search函数为搜索：从开头到‘（’为止的所有字符；.group是为了提取出字符串
            # sub函数为替换：将‘（’到结尾的所有字符删除。（用来去括号，目前没想到什么更好的办法）
            pattern = re.sub(r'\(.*$', "", re.search(r'^.*\(', line).group())
            file2.write(pattern + "_ret;\n")
            file2.write(line)
            # 写入返回值，sub函数：将返回值类型去除
            temp = "\treturn A" + re.sub(r'^.*A', "", pattern) + "_ret;\n"
        elif "}" in line:
            file2.write(temp)
            file2.write(line)
            temp = ""
        else:
            file2.write(line)
        if not line:
            break

    file1.close()
    file2.close()
    print("end:	write ret")
    return


def write_val(path):
    print("start:	write val")
    file2 = open(path + 'STUB_SrcFile_temp2.c', 'r+')
    file3 = open(path + 'STUB_SrcFile_new.c', 'a')
    val_flg = 0
    while True:
        # rolling3 : 加上参数.....的标识
        line = file2.readline()

        if " STUB_" in line and "()" not in line and not ";" in line:
            val_flg = 1
            # file3.write("引数here")
            pattern = re.sub(r'\(.*$', "", re.search(r'A.*\(', line).group())
            # ###val-try  start####
            val_amount = line.count

            # 取出括号里的内容并去括号
            val_all = re.sub(
                r'\)', "", re.sub(r'\(', "",
                                  re.search(r'\(.*\)', line).group()))
            num_val = val_all.count(",") + 1
            list_val_all = re.split('[,]', val_all)
            num = 0
            while num < num_val:
                num_val_space = list_val_all[num].count(" ")
                list_val_temp = re.split('\s', list_val_all[num])
                if num_val > 1:
                    if num_val_space > 1:
                        temp = list_val_temp[0] + " " + list_val_temp[
                            1] + " " + pattern + "_val" + str(num + 1) + ";"
                    else:
                        temp = list_val_temp[0] + " " + pattern + "_val" + str(
                            num + 1) + ";"
                else:
                    if num_val_space > 1:
                        temp = list_val_temp[0] + " " + list_val_temp[
                            1] + " " + pattern + "_val" + "1;"
                    else:
                        temp = list_val_temp[0] + " " + pattern + "_val" + "1;"

                file3.write(temp)
                file3.write("\n")
                # pattern = re.split('\W+',pattern)
                # print("it's %d here" %num_val)
                # print(list_val_temp[0]+" "+list_val_temp[1]+" "+ "val%d" %num)
                num = num + 1
            # ###val-try  end####
            file3.write(line)
        elif "cnt++" in line and val_flg == 1:
            file3.write(line)
            num = 0
            while num < num_val:
                print("aaaaa")
                num_val_space = list_val_all[num].count(" ")
                list_val_temp = re.split('\s', list_val_all[num])
                file3.write("\t" + pattern +"_val" + str(num + 1) + " = " + list_val_temp[-1] + ";\n")
                num = num + 1

            val_flg = 0

        else:
            file3.write(line)
        if not line:
            break
    file2.close()
    file3.close()
    print("end:	write val")
    return


if __name__ == "__main__":
    print("\nStart")
    path = sys.argv[1]
    # if judge_new() == 1:
    del_useless(path)
    del_blank(path)
    write_cnt(path)
    write_ret(path)
    write_val(path)

    os.remove(path + 'STUB_SrcFile_temp.c')
    os.remove(path + 'STUB_SrcFile_temp_no_enter.c')
    os.remove(path + 'STUB_SrcFile_temp1.c')
    os.remove(path + 'STUB_SrcFile_temp2.c')

    print("\nPlease press \"L\" to end program")
    msvcrt.getch()
